package com.mc.moring.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.gyf.immersionbar.ImmersionBar;
import com.mc.moring.R;
import com.mc.moring.app.LogUtils;
import com.mc.moring.base.BaseActivity;
import com.mc.moring.base.BaseModle;
import com.mc.moring.base.HttpCallback;
import com.mc.moring.bean.WebPageContentBean;
import com.mc.moring.login.LoginActivity;
import com.mc.moring.main.modle.PermisosModle;
import com.mc.moring.util.GsonUtils;
import com.mc.moring.util.PointMgr;
import com.mc.moring.util.SharePreUtil;
import com.mc.moring.util.UriUtils;
import com.mc.moring.view.AndroidBug5497Workaround;
import com.mc.moring.util.ZhiliDeviceUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class WebViewActivity extends BaseActivity {
    private ImageButton abBackIBtn;
    private TextView abTitleTV;
    private ValueCallback<Uri[]> mFilePathCallback;
    WebView web;
    private ImageView web_Image;
    private String name = "";
    private String phone = "";

    private String type = "";

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url = getIntent().getStringExtra("url");

        type = getIntent().getStringExtra("type");
        name = SharePreUtil.getStringData("webName");
        phone = SharePreUtil.getStringData("webPhone");
        setContentView(R.layout.activity_web_view);
        abBackIBtn = findViewById(R.id.abBackIBtn);
        web = findViewById(R.id.web_view);
        abTitleTV = findViewById(R.id.abTitleTV);
        web_Image = findViewById(R.id.web_Image);
        abTitleTV.setText("Página web");
        abBackIBtn.setOnClickListener(v -> finish());
        LogUtils.logE("url>" + url);
        web.setWebViewClient(new MyWebViewClient());



        WebSettings settings = web.getSettings();
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);

        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true);

        settings.setAllowContentAccess(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setMediaPlaybackRequiresUserGesture(false);

        settings.setLoadWithOverviewMode(true);
        settings.setBuiltInZoomControls(true);

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
            settings.setDisplayZoomControls(false);
        }

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            web.setWebContentsDebuggingEnabled(true);
        }

        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);

        web.addJavascriptInterface(new JavaScriptInterface(this, web, this),"moniApp");
        web.setDrawingCacheEnabled(true);
        web.setWebChromeClient(new WebViewChromeClient(this, this));
        AndroidBug5497Workaround.assistActivity(this);
        if (TextUtils.isEmpty(type)) {
            web.loadUrl(url);
            return;
        }
        if (type.equals("privacyAgree")) {
            loadPrivacyAgree(url);
        } else {
            web.loadUrl(url);
        }
        web.evaluateJavascript("javascript:lwApp.uploadAppEvent(\"video_21_upload_yes\")", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                PointMgr.INSTANCE.sendEvent("cl_video_21_upload_yes");
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_video_21_upload_yes");
            }
        });
    }

    private void loadPrivacyAgree(String url) {
        Map<String, String> webContentMap = new HashMap<>();
        webContentMap.put("pageType","privacyPolicy");
        showLoading();
        PermisosModle.Companion.getInstant().getWebPageContent(webContentMap, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                WebPageContentBean webPageContentBean = GsonUtils.INSTANCE.getGson().fromJson(data, WebPageContentBean.class);
                if (webPageContentBean.getCode().equals("0000") && !TextUtils.isEmpty(webPageContentBean.getData())) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String webContent = webPageContentBean.getData();
                            web.getSettings().setUseWideViewPort(false);
                            web.getSettings().setLoadWithOverviewMode(false);
                            web.loadData(webContent, "text/html","UTF-8");
                        }
                    });
                } else {
                    web.loadUrl(url);
                }
                hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                hideLoading();
            }
        });
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (handler != null) {
                handler.proceed();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            if (!url.startsWith("http")) {
                return true;
            }
            return super.shouldOverrideUrlLoading(view, request);
        }
    }
    public class WebViewChromeClient extends WebChromeClient implements com.mc.moring.main.WebViewChromeClient {
        private Context _context;
        private Activity _m;
        public WebViewChromeClient(Context context, Activity mainActivity)
        {
            _context = context;
            _m = mainActivity;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (TextUtils.isEmpty(type)) {
                abTitleTV.setText(title);
                return;
            }
            if (type.equals("privacyAgree")) {
                abTitleTV.setText("Política de privacidad");
            } else {
                abTitleTV.setText(title);
                if ( title.contains("de pago") ){
                    web_Image.setVisibility(View.GONE);
                }
            }

        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mFilePathCallback = filePathCallback;
            Log.e("----111","onShowFileChooser");
//            if ( Build.VERSION.SDK_INT > 32 ){
//                Log.e("----1111","onShowFileChooser");
//                openAlbum();
//            } else {
//                if (ContextCompat.checkSelfPermission(WebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//                    Log.e("----1112","onShowFileChooser");
//                    String[] list = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
//                    ActivityCompat.requestPermissions(WebViewActivity.this, list, 0x1001);
//                } else {
//                    Log.e("----1113","onShowFileChooser");
//                    openAlbum();
//                }
//            }
            Log.e("----1111","onShowFileChooser");
            openAlbum();
            return true;
        }

        private void openAlbum(){
            Log.e("----111","GET_CONTENT");
            Intent intent = new Intent("android.intent.action.GET_CONTENT");
            intent.setType("image/*");
            startActivityForResult(intent, 0X101);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("----111","onActivityResult");
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0x101:
                    Log.e("----111","1x101");
                        try {
                            Uri uri = data.getData();
                            String picturePath = UriUtils.getFileAbsolutePath(this,uri);
                            Bitmap bm = compressImage(BitmapFactory.decodeFile(picturePath));
                            String result = saveBitmap(bm);
                            if (result == null || result.isEmpty()) {
                                result = outputImage.getAbsolutePath();
                            }
                            File file = new File(result);
                            Uri uri2 = Uri.fromFile(file);
                            Uri[] uris = new Uri[]{uri2};
                            Log.e("---111uri", Arrays.toString(uris));
                            sendImage(uris);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    break;

                case 0x102:
                    Log.e("----111","1x102");
                        try {
    //                        RequestOptions options = new RequestOptions().placeholder(R.mipmap.icon_avatar_0);
    //                        Glide.with(this).load(outputImage).apply(options).into(image_cover);
                            Bitmap bm = compressImage(
                                    BitmapFactory.decodeFile(
                                            outputImage.getAbsolutePath()
                                )
                            );
                            String result = saveBitmap(bm);
                            if (result == null || result.isEmpty()) {
                                result = outputImage.getAbsolutePath();
                            }
                            File file = new File(result);
                            Uri uri2 = Uri.fromFile(file);
                            Uri[] uris = new Uri[]{uri2};
                            sendImage(uris);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    break;
            }
        } else {
            Log.e("----1111","onActivityResult");
            sendImage(null);
        }
    }

    private String saveBitmap(Bitmap bitmap){
        Log.e("----111","saveBitmap");
        if (bitmap == null) return null;
        File file = new File(this.getExternalCacheDir(), String.valueOf(System.currentTimeMillis()) + "_image.jpg");
        Log.e("---111file",file.toString());
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return file.getAbsolutePath();
    }

    private void sendImage(Uri[] uris) {
        Log.e("----111","sendImage");
        if (mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(uris);
            mFilePathCallback = null;
        }
    }

    public Bitmap compressImage(Bitmap image){
        Log.e("----111","compressImage");
        if (image == null) return null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(
                Bitmap.CompressFormat.JPEG,
                100,
                baos
        ); // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 50;
        while (baos.toByteArray().length / 1024 > 1000) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            Log.e("----111","compress");
            baos.reset(); // 重置baos即清空baos
            image.compress(
                    Bitmap.CompressFormat.JPEG,
                    options,
                    baos
            ); // 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10; // 每次都减少10
        }
        ByteArrayInputStream isBm =
                new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);
    }


    public class JavaScriptInterface {
        private Context context;
        private WebView webView;
        private Activity activity;
        public JavaScriptInterface(Context context, WebView webView, Activity mainActivity)
        {
            this.context = context;
            this.webView = webView;
            this.activity = mainActivity;
        }

        @JavascriptInterface
        public String getMoniInfo(){
            Log.e("----111getMoniInfo", "----1");
            if (isFinishing()){
                return "";
            }
            String result = "";
            Map<String, Object> headers = new BaseModle().getZiLiPageHead();
            headers.put("apiHost", "https://backend.moni-cash.com/");
            headers.put("deviceId", ZhiliDeviceUtils.INSTANCE.getDeviceID(activity));
            headers.put("strategy", "default");
            headers.put("country", "51");
            headers.put("User-Agent", "Retrofit-Sample-App");

            headers.put("phone",phone);
            headers.put("name",name);
            result = GsonUtils.INSTANCE.getGson().toJson(headers);
            Log.e("----result",result);
            return result;
        }

        @JavascriptInterface
        public void toMiFirstPage(){
            Log.e("----111toMiFirstPage", "----1");
            if (isFinishing()){
                return;
            }
            finish();
        }

        @JavascriptInterface
        public void tokeNeedRefresh(){
            Log.e("----111tokeNeedRefresh", "----1");
            if (isFinishing()){
                return;
            }
        }

        @JavascriptInterface
        public void tokenOverdue(){
            Log.e("----111tokenOverdue", "----1");
            Intent intent = new Intent(activity, LoginActivity.class);
            startActivity(intent);
            finish();
        }

        @JavascriptInterface
        public void loadPage(String url, int type){
            Log.e("----111loadPage", "----1");
            if (isFinishing()){
                return;
            }
            System.out.println("FlyloAn...loadPage"+url);
            Intent intent = new Intent(activity, WebViewActivity.class);
            intent.putExtra("url", url);
            startActivity(intent);
            finish();
        }

        @JavascriptInterface
        public void openShare(String url){
            if (isFinishing()){
                return;
            }
        }

        @JavascriptInterface
        public void uploadAppEvent(String event){
            PointMgr.INSTANCE.sendEvent(event);
            Log.e("PointMgr.INSTANCE.sendEvent", event);
            if (isFinishing()){
                return;
            }
        }

        @JavascriptInterface
        public void loanImprest(){
            if (isFinishing()){
                return;
            }
        }

        @JavascriptInterface
        public void toMoniHomePage(){
            LogUtils.logE("---JavaScriptInterface: toMoniHomePage---");
            finish();
        }
    }

    @Override
    public Activity getActivity() {
        return null;
    }

    @Override
    public void initView() {

    }


    @Override
    public void initData() {

    }

    @Override
    public void onStop(){
        super.onStop();
        hideLoading();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            web.clearCache(true);
            web.removeJavascriptInterface("moniApp");
            web.clearFormData();
            web.clearHistory();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e("----111","onRequestPermissionsResult");
        switch (requestCode) {
            case 0x1002:
                Log.e("----111","0x1002");
                boolean accepted = true;
                int i = 0;
                while (i < grantResults.length) {
                    boolean acceptedTmp = grantResults[i] == PackageManager.PERMISSION_GRANTED;
                    if (!acceptedTmp) {
                        accepted = false;
                    }
                    i++;
                }
                if (accepted) {
                    openTake();
                } else {
                    sendImage(null);
                }
                break;

            case 0x1001:
                Log.e("----111","0x1001");
                boolean accepted2 = true;
                int i2 = 0;
                while (i2 < grantResults.length) {
                    boolean acceptedTmp = grantResults[i2] == PackageManager.PERMISSION_GRANTED;
                    if (!acceptedTmp) {
                        //用户同意了权限
                        accepted2 = false;
                    }
                    i2++;
                }
                if (accepted2) {
                    openAlbum();
                } else {
                    sendImage(null);
                }
                break;
        }
    }

    private Uri imageUri = null;
    private File outputImage = null;

    private void openTake() {
        Log.e("----111","openTake");
        outputImage =
                new File(this.getExternalCacheDir(), "output_image_" + System.currentTimeMillis() + ".jpg");
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(this, "com.papa.mimi.fileprovider", outputImage);
        } else {
            imageUri = Uri.fromFile(outputImage);
        }
        Log.e("----111","IMAGE_CAPTURE");
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, 0x102);
    }

    private void openAlbum() {
        Log.e("----1112","GET_CONTENT");
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, 0X101); //打开相册
    }
}
